package net.ulrice.mdls.richclient;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;

import javax.swing.AbstractAction;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

import net.ulrice.configuration.ConfigurationException;

import org.apache.thrift.TException;

public class StartupDialog extends JFrame {

	private static final long serialVersionUID = 1L;

	public StartupDialog() {
		super();
		setUndecorated(true);
		
		final JTextField urlField = new JTextField("localhost:9090");
		urlField.setMargin(new Insets(4, 4, 4, 4));
		
		JButton okButton = new JButton(new AbstractAction("OK") {
			
			private static final long serialVersionUID = 1L;

			@Override
			public void actionPerformed(ActionEvent e) {				
				try {
					dispose();
					Richclient.connect(urlField.getText());
				} catch (ConfigurationException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				} catch (TException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			}

		});
		JButton cancelButton = new JButton(new AbstractAction("Cancel") {
			
			private static final long serialVersionUID = 1L;

			@Override
			public void actionPerformed(ActionEvent arg0) {
				System.exit(0);
			}

		});
		
		getRootPane().setDefaultButton(okButton);

		JPanel buttonPanel = new JPanel(new GridLayout(1, 2, 10, 0));
		buttonPanel.setBorder(BorderFactory.createEmptyBorder(4, 10, 0, 10));
		buttonPanel.setOpaque(false);
		buttonPanel.add(okButton);
		buttonPanel.add(cancelButton);
		
		JPanel bottomPanel = new JPanel(new GridLayout(2, 1));
		bottomPanel.setOpaque(false);
		bottomPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
		bottomPanel.add(urlField);
		bottomPanel.add(buttonPanel);
		
		JLabel iconLabel = new JLabel(new ImageIcon(StartupDialog.class.getResource("meltdown.png")));
		iconLabel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
		JPanel mainPanel = new JPanel(new BorderLayout());
		mainPanel.setBorder(BorderFactory.createLineBorder(Color.DARK_GRAY));
		mainPanel.setBackground(Color.WHITE);
		mainPanel.add(iconLabel, BorderLayout.CENTER);
		mainPanel.add(bottomPanel, BorderLayout.SOUTH);
		
		setContentPane(mainPanel);
		
		pack();
		setLocationRelativeTo(null);
		setVisible(true);	
	}

	public static void showDialog() {
		new StartupDialog();
	}
}
